<?php
    
    function __realpath($path) {
        $path = str_replace('\\','/',realpath($path));
        if ($path{1} == ':') {
            // We can't just check for C:/, because windows users may have the IIS webroot on X: or F:, etc.
            $path = substr($path,2);
        }
        return $path;
    }
    
    // TODO: check CURL : show error if there is no CURL
    
    include("func.php");
    define('EXPONENT', "ABSoft - Auto backup data authorization");
    define('BASE',__realpath(dirname(__FILE__)).'/../');
    include(BASE."auto_backup/kurtulus_autobackup_config/config.php");
    require_once BASE.'auto_backup/google-api-php-client/src/Google_Client.php';
    require_once BASE.'auto_backup/google-api-php-client/src/contrib/Google_DriveService.php';

    
    
    $client = new Google_Client();
    // Get your credentials from the APIs Console
    $client->setClientId(CLIENT_ID);
    $client->setClientSecret(SECRET_ID);
    $client->setRedirectUri(REDIRECT);
    //Sonhb - Access only create
    $client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
    if($_REQUEST['action']=='refresh')
    {
        $tok=json_decode(base64_decode(file_get_contents(BASE.'auto_backup/kurtulus_autobackup_config/tok.kurtulus')));
        if($tok->refresh_token)
        {
        $client->refreshToken($tok->refresh_token);
        $accessToken = $client->getAccessToken();
        $fh = fopen(BASE.'auto_backup/kurtulus_autobackup_config/tok.kurtulus', 'w');
        fwrite($fh, $accessToken);
        fclose($fh);
        echo 'refreshed';
        }
        else
        {
           echo 'Not refresh'; 
        }
        exit();
    }
    if (isset($_GET['code'])) {
        $client->authenticate();
        $accessToken = $client->getAccessToken();
        $fh = fopen(BASE.'auto_backup/kurtulus_autobackup_config/tok.kurtulus', 'w');
        fwrite($fh, base64_encode($accessToken));
        fclose($fh);
        echo 'Authorization complete!';
        exit();
    }
    else
    {
        $authUrl = $client->createAuthUrl();
        header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
    }
?>
